package com.fz.aop.login;

import com.fz.common.Global;
import com.fz.common.ResponseEntity;
import com.fz.common.ResultCode;
import com.fz.security.config.SecurityProperties;
import com.fz.utils.RedisUtil;
import com.fz.utils.SpringContextUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class SiteLoginAspect {
    private static final Logger logger = LoggerFactory.getLogger(SiteLoginAspect.class);

    @Autowired
    RedisUtil redisUtils;

    //定义切面
    @Pointcut("!@annotation(com.fz.aop.login.AnonymousAccess)"+
            "&& execution(* com.fz.controller..*(..))")
    public void siteLoginPointCut() {

    }

    @Around("siteLoginPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        SecurityProperties properties = SpringContextUtil.getBean(SecurityProperties.class);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String requestHeader = request.getHeader(properties.getHeader());
        String token =  requestHeader.substring(7);
        logger.debug("切面中获取token："+token);
        //判断账号是否被占用
        if(redisUtils.hasKey(Global.OLD_TOKEN + token)){
            return ResponseEntity.build(ResultCode.OFF_SITE_LOGIN);
        }
        Object o = joinPoint.proceed();
        return o;
    }
}
